package com.engine.core.rowMapper;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MappedTypeRowMapper implements RowMapper<Map<String,Object>> {

    private Map<Integer,String> typeFormat;
    protected static final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
    private Map<String,MappedType> formatMap;


    public MappedTypeRowMapper(Map<Integer,String> typeFormat,Map<String,MappedType> formatMap){
        this.formatMap=formatMap;
        this.typeFormat=typeFormat;
    }
    /**
     * @param rs
     * @param rowNum
     * @return
     * @throws SQLException
     */
    @Override
    public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        Map<String,Object> rmap=new HashMap<>();
        int columnCount = metaData.getColumnCount();
        for(int a=1;a<=columnCount;a++ ) {
            String label = metaData.getColumnLabel(a);
            //java.sql.Types
            int sqltype = metaData.getColumnType(a);
            Object o=typeHandlerRegistry.getTypeHandler(JdbcType.forCode(sqltype)).getResult(rs,label);
            if(formatMap.containsKey(label) && !StringUtils.isEmpty(formatMap.get(label).getFormat())){
                o=JdbcTypeBiz.userFormat(o,formatMap.get(label),sqltype,rs);
            }else if(typeFormat.containsKey(sqltype)){
                o=JdbcTypeBiz.sqlTypeFormat(o,sqltype,typeFormat);
            }
            rmap.put(label,o);
        }
        return rmap;
    }
}
